package cn.tom.service;


import cn.hutool.core.util.StrUtil;
import cn.tom.exceptiom.TomException;
import cn.tom.tool.RedisCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;

import javax.mail.internet.MimeMessage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class MailServiceImpl implements MailService {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Autowired(required = false)
    JavaMailSenderImpl mailSender;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    RedisCache redisCache;

    /**
     * 读取邮件模板
     * 替换模板中的信息
     *
     * @param title 内容
     * @return
     */
    public String buildContent(String title) {
        //加载邮件html模板
        Resource resource = new ClassPathResource("freemaker/mailtemplate.ftl");
        InputStream inputStream = null;
        BufferedReader fileReader = null;
        StringBuffer buffer = new StringBuffer();
        String line = "";
        try {
            inputStream = resource.getInputStream();
            fileReader = new BufferedReader(new InputStreamReader(inputStream));
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            log.info("发送邮件读取模板失败{}", e);
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //替换html模板中的参数
        return MessageFormat.format(buffer.toString(), title);
    }

    @Override
    public void setCaptcha(String key) {
        //ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        String captcha1 = redisCache.getCacheObject(key);
        if (StrUtil.isNotBlank(captcha1)) {
            throw new TomException("请勿频繁发送验证码");
        }
        //Jedis jedis = jedisUtils.getJedis();
        String captcha = creatCode(5);

        /*jedis.set(key,captcha,new SetParams().ex(300)); //有效时间300秒
        jedisUtils.close(jedis); //释放资源*/
        //ops.set(key,captcha,300,TimeUnit.SECONDS); TimeUnit.MINUTES


        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom("2360503341@qq.com"); //发件人
        message.setTo(key); //收件人
        message.setSubject("悦读书城 注册验证"); //主题
        //message.setText("您好，"+ key +"您的悦读图书商城的注册验证码是: " +captcha +"验证码仅5分钟有效请尽快注册,如非本人操作请忽略此次请求,请不要回复此邮件"); //内容
        message.setText(buildContent(captcha + ""));
        mailSender.send(message);
        redisCache.setCacheObject(key, captcha, 300, TimeUnit.SECONDS);
    }

    @Override
    public String getCaptcha(String key) {
        //ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
        //Jedis jedis = jedisUtils.getJedis();
        // String captcha = ops.get(key);
        String captcha = redisCache.getCacheObject(key);
       /* if (jedis.exists(key)) {
            captcha = jedis.get(key);
            log.info(key + "是在Redis中查询的验证码数据值是：" + captcha);
            jedisUtils.close(jedis); //释放资源
            return captcha;
        }
        jedisUtils.close(jedis); //释放资源*/
        return captcha;
    }

    public String creatCode(int n) {
        //3、定义一个字符串变量记录生成的随机字符
        String code = "";
        Random r = new Random();
        //2、定义一个for循环，循环n次，依次生成随机字符
        for (int i = 0; i < n; i++) {
            //i=0 1 2
            //3、生成一个随机字符，英文大、小写 数字（0 1 2 ）
            int type = r.nextInt(3);//0 1 2
            switch (type) {
                case 0:
                    //大写字符（A 65-Z 65+25）
                    char ch = (char) (r.nextInt(26) + 65);
                    code += ch;
                    break;
                case 1:
                    //小写字符（a 97-z 97+25）
                    char ch1 = (char) (r.nextInt(26) + 97);
                    code += ch1;
                    break;
                case 2:
                    //数字字符
                    code += r.nextInt(10);//0-9
                    break;
            }
        }
        return code;
    }
}
